import os

from utils import doc_util, html_util, json_util, date_util, read_config as config, excel_util
from service import score_service, data_service
from methods import d月macd穿过0方法验证 as month_macd_service

result_path = os.path.join(config.data_path, 'result', '突破均线')
users_path = os.path.join(config.data_path, 'common', 'users')
config_path = os.path.join(config.data_path, 'common', 'config')
trigger_logs_path = os.path.join(config.data_path, 'logs', '突破均线任务1')


# 月线验证
def month_validation(date):
    s_dict = data_service.new_stock_all()
    result_path = os.path.join(config.data_path, 'result', '月macd', date, '历史验证')
    count = 0
    while (not os.path.exists(result_path)) or count > 4:
        count += 1
        date = date_util.add_day_str(date, -1)
        result_path = os.path.join(config.data_path, 'result', '月macd', date, '历史验证')
    s_list = []
    if not os.path.exists(result_path):
        for code in s_dict:
            s_list.append(s_dict[code])
        month_macd_service.month_macd_valid(s_list, date)
    excel_arr = excel_util.get_excel_info(os.path.join(result_path, '000000.xlsx'), '')
    checkout_dict = doc_util.get_a_doc_dict(os.path.join(result_path, '999999'), 'code')
    if (len(excel_arr) - 1) != len(s_dict.keys()):
        file_name_dict = {}
        for i in range(1, len(excel_arr)):
            file_name_dict[excel_arr[i][0]] = 1
        for code in s_dict:
            if code not in file_name_dict.keys() and code not in checkout_dict.keys():
                s_list.append(s_dict[code])
        month_macd_service.month_macd_valid(s_list, date)
    path = os.path.join(result_path, '000000.xlsx')
    path = path.replace('\\', '*').replace('/', '*')
    file_url = 'http://' + config.domain + '/download/doc/' + path
    return html_util.get_button_href(file_url, '点击下载验证结果')


# 获取指定日期的结果
def trigger_result(date):
    path = os.path.join(config.data_path, 'task', 'document', '突破均线', 'stock_monitor_dict')
    monitor_dict = doc_util.get_a_doc_dict(path, 'code')
    file_dict = {}
    up_flag = 0
    for code in monitor_dict.keys():
        monitor_info = json_util.info_to_json(monitor_dict[code])
        code = monitor_info['code']
        name = monitor_info['name']
        if 'trigger_time' not in monitor_info.keys():
            continue
        trigger_time = monitor_info['trigger_time']
        if trigger_time[0:10] != date_util.get_date_str():
            continue
        result_file_path = monitor_info['result_file_path']
        if 'score_info' not in monitor_info:
            up_flag = 1
        else:
            score_info = monitor_info['score_info']
            if 'exam_time' in score_info.keys():
                exam_time = score_info['exam_time']
                if (date_util.get_timestamp_now() - exam_time) > 600:
                    up_flag = 1
            else:
                up_flag = 1
        if up_flag == 1:
            monitor_info = score_service.common_exam(monitor_info)
            monitor_dict[code] = monitor_info
        score_info = json_util.info_to_json(monitor_info['score_info'])
        level = score_info['level']
        if 'trigger_time' not in monitor_info.keys():
            monitor_info['trigger_time'] = '2000-01-01 00:00:00'
            monitor_info['trigger_timestamp'] = date_util.datetime2timestamp('2000-01-01 00:00:00')
        trigger_time = monitor_info['trigger_time']  # 触发时间
        result_file_path = '当前' + result_file_path
        if result_file_path not in file_dict.keys():
            file_dict[result_file_path] = []
        file_list = []
        file_name = name + ':' + code + '--触发时间:' + trigger_time[0:10] + '--等级:' + level
        file_url = 'http://' + config.domain + '/download/position/' + date + '/' + result_file_path + '*' + file_name
        file_list.append(file_name)
        file_list.append(file_url)
        file_dict[result_file_path].append(file_list)
    if up_flag:
        doc_util.gen_a_doc(os.path.join(config.data_path, 'task', 'document', '突破均线'), 'stock_monitor_dict',
                           monitor_dict)
    return html_util.get_form_list_actual('仓位情况' + date, file_dict)


# 获取指定日期的结果
def position_result(user_code, date):
    path = os.path.join(config.data_path, 'task', 'document', '突破均线', 'stock_monitor_dict')
    monitor_dict = doc_util.get_a_doc_dict(path, 'code')
    file_dict = {}
    up_flag = 0
    user_m_dict = monitor_dict
    if user_code != '':
        if os.path.exists(os.path.join(users_path, user_code)):
            user_m_dict = doc_util.get_a_doc_dict(os.path.join(users_path, user_code), 'code')
    for code in monitor_dict.keys():
        if code not in user_m_dict.keys():
            continue
        monitor_info = json_util.info_to_json(monitor_dict[code])
        code = monitor_info['code']
        name = monitor_info['name']
        result_file_path = monitor_info['result_file_path']
        if 'score_info' not in monitor_info:
            up_flag = 1
        else:
            score_info = monitor_info['score_info']
            if 'exam_time' in score_info.keys():
                exam_time = score_info['exam_time']
                if (date_util.get_timestamp_now() - exam_time) > 600:
                    up_flag = 1
            else:
                up_flag = 1
        if up_flag == 1:
            monitor_info = score_service.common_exam(monitor_info)
            monitor_dict[code] = monitor_info
        score_info = json_util.info_to_json(monitor_info['score_info'])
        level = score_info['level']
        if 'trigger_time' not in monitor_info.keys():
            monitor_info['trigger_time'] = '2000-01-01 00:00:00'
            monitor_info['trigger_timestamp'] = date_util.datetime2timestamp('2000-01-01 00:00:00')
        trigger_time = monitor_info['trigger_time']  # 触发时间
        result_file_path = '当前' + result_file_path
        if result_file_path not in file_dict.keys():
            file_dict[result_file_path] = []
        file_list = []
        file_name = name + ':' + code + '--触发时间:' + trigger_time[0:10] + '--等级:' + level
        file_url = 'http://' + config.domain + '/download/position/' + date + '/' + result_file_path + '*' + file_name
        file_list.append(file_name)
        file_list.append(file_url)
        file_dict[result_file_path].append(file_list)
    if up_flag:
        doc_util.gen_a_doc(os.path.join(config.data_path, 'task', 'document', '突破均线'), 'stock_monitor_dict',
                           monitor_dict)
    return html_util.get_form_list_actual('仓位情况' + date, file_dict)


# 获取股票最近触发情况
def get_trigger_info(date, code):
    log_list = doc_util.get_doc_str_list(os.path.join(trigger_logs_path, 'out.log'))
    content_arr = []
    for log in log_list:
        if log[0:15] != 'triggerthedeal:':
            continue
        stock_info = json_util.info_to_json(log.split('triggerthedeal:')[1])
        if stock_info['code'] == code:
            name = stock_info['name']
            trigger_time = '2000-01-01'
            if 'trigger_time' in stock_info.keys():
                trigger_time = stock_info['trigger_time']
            # 展示今年的
            if date_util.date_to_timestamp(trigger_time[0:10]) < 1613836800:
                continue
            deal_price = 0
            if 'deal_price' in stock_info.keys():
                deal_price = str(stock_info['deal_price'])
            result_file_path = '未触发'
            if 'result_file_path' in stock_info.keys():
                result_file_path = stock_info['result_file_path']
            sb_io = '未记录'
            b_io = '未记录'
            hsl = '未记录'
            if 'sb_io' in stock_info.keys():
                sb_io = str(round(stock_info['sb_io'] / 10000)) + '万'
                b_io = str(round(stock_info['b_io'] / 10000)) + '万'
                hsl = str(stock_info['hsl'])
            score_level = '未分级'
            if 'score_info' in stock_info.keys():
                score_info = json_util.info_to_json(stock_info['score_info'])
                score_level = score_info['level']
            data = []
            data.append(code)
            data.append(name)
            data.append(trigger_time[0:10])
            data.append(trigger_time)
            data.append(deal_price)
            data.append(str(stock_info['ave5']))
            data.append(str(stock_info['ave10']))
            data.append(result_file_path)
            data.append(stock_info['macd'])
            data.append(sb_io)
            data.append(b_io)
            data.append(hsl)
            data.append(score_level)
            content_arr.append(data)
    content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
                        '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '评分等级'])
    content_arr.reverse()
    return html_util.get_a_table(content_arr)


# 获取路径下所有文档
def file_path_names(path):
    return format_result2(path, '/download/doc/', '文档情况')


# 格式化整理2
def format_result2(path, down_url, title):
    file_list = doc_util.get_file_path_names(path)
    file_dict = {}
    for file_path_name in file_list:
        download_path = file_path_name.replace('\\', '*')
        file_path_name = file_path_name.split(path + '\\')[1]
        file_down_url = 'http://' + config.domain + down_url + '/' + download_path
        names = file_path_name.split('\\')
        names[-1] = {'url': file_down_url, 'name': names[-1]}
        if len(names) == 1:
            names = ['当前文档内容'] + names
        file_dict = dg_dict(file_dict, names)
    return html_util.get_form_list_actual(title, file_dict)


# 递归dictionary
# file_dict={'path1':{'path11':{path111':[],'path112':[]},'path12':{}},'path2':{}}
# name = [path1,path11,path111,{}]
def dg_dict(file_dict, names):
    names_len = len(names)
    for i in range(names_len):
        if isinstance(names[i], dict):
            file_dict.append(names[i])
            return file_dict
        else:
            name = names[i]
            if name not in file_dict.keys():
                if i == names_len - 2:
                    file_dict[name] = []
                else:
                    file_dict[name] = {}
            file_dict[name] = dg_dict(file_dict[name], names[1:names_len])
            return file_dict
